package com.baturu.vin.hyundai.service.impl;

import com.baturu.vin.base.exception.EPCDataNotStandardException;
import com.baturu.vin.hyundai.dal.dao.HyundaiKiaFeatureDAO;
import com.baturu.vin.hyundai.dal.entity.HyundaiKiaFeatureEntity;
import com.baturu.vin.hyundai.dto.FeatureInfoDTO;
import com.baturu.vin.kit.StreamKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class HyundaiKiaFeatureService {

    @Autowired
    private HyundaiKiaFeatureDAO featureDAO;

    /**
     * 从源数据集中整理特征信息，vinInfo[2]中大概为功能代码
     *
     * @param featureArr 特征源数据
     * @return 特征数据信息
     */
    public FeatureInfoDTO getFeatureInfo(String[] featureArr) throws EPCDataNotStandardException {
        if (Objects.isNull(featureArr) || featureArr.length <= 0) {
            return null;
        }
        // 数据基本符合以下逻辑，每4个为一个特征信息
        // N * 4 + 0 (N > 0) 特征编码
        // N * 4 + 1 (N > 0) 特征说明
        // N * 4 + 2 (N > 0) 特征类型
        // N * 4 + 3 (N > 0) 特征标记
        // last = ""
        int startSkipSize = 0;
        int lastFallbackSize = 1;
        int featureDescSize = 4;

        List<HyundaiKiaFeatureEntity> result = new ArrayList<>();
        for (int startIndex = startSkipSize, endIndex = featureArr.length - 1 - lastFallbackSize; startIndex < endIndex; startIndex += featureDescSize) {
            HyundaiKiaFeatureEntity feature = new HyundaiKiaFeatureEntity();
            feature.setCode(featureArr[startIndex]);
            feature.setMessage(featureArr[startIndex + 1].trim());
            feature.setType(featureArr[startIndex + 2].trim());
            feature.setModel(featureArr[startIndex + 3].trim());
            result.add(feature);
        }
        return new FeatureInfoDTO(result);
    }

    /**
     * 检查特征是否存在并存储新增特征信息
     *
     * @param featureInfo 特征信息集
     */
    public void checkAndSaveFeatureInfo(FeatureInfoDTO featureInfo, String lang) {
        if (Objects.isNull(featureInfo)) {
            return;
        }
        try {
            List<HyundaiKiaFeatureEntity> data = featureInfo.getData();
            data.forEach(d -> d.setMessage(StringUtils.replace(d.getMessage(), "'", "’")));
            if (CollectionUtils.isNotEmpty(data)) {
                StreamKit.partitionStream(data, 200).forEach(l -> featureDAO.save(l, lang));
            }
        }catch (Exception e){
            log.warn("现代起亚存储配件出错：{}",e.toString());
        }

    }
}